import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';

class FCMService {
  static final FCMService _instance = FCMService._internal();
  factory FCMService() => _instance;
  FCMService._internal();

  final FirebaseMessaging _firebaseMessaging = FirebaseMessaging.instance;
  String? _fcmToken;
  bool _isInitialized = false;

  // 获取 FCM Token
  Future<String?> getFCMToken() async {
    try {
      if (!_isInitialized) {
        debugPrint('FCM 服务未初始化，请先调用 initialize()');
        return null;
      }

      // 请求通知权限
      NotificationSettings settings = await _firebaseMessaging
          .requestPermission(
            alert: true,
            announcement: false,
            badge: true,
            carPlay: false,
            criticalAlert: false,
            provisional: false,
            sound: true,
          );

      if (settings.authorizationStatus == AuthorizationStatus.authorized) {
        // 获取 FCM Token
        _fcmToken = await _firebaseMessaging.getToken();
        debugPrint('FCM Token: $_fcmToken');

        return _fcmToken;
      } else {
        debugPrint('用户拒绝了通知权限');
        return null;
      }
    } catch (e) {
      debugPrint('获取 FCM Token 失败: $e');
      return null;
    }
  }

  // 订阅主题
  Future<bool> subscribeToTopic(String topic) async {
    try {
      if (!_isInitialized) {
        debugPrint('FCM 服务未初始化');
        return false;
      }

      await _firebaseMessaging.subscribeToTopic(topic);
      debugPrint('成功订阅主题: $topic');
      return true;
    } catch (e) {
      debugPrint('订阅主题失败: $e');
      return false;
    }
  }

  // 取消订阅主题
  Future<bool> unsubscribeFromTopic(String topic) async {
    try {
      if (!_isInitialized) {
        debugPrint('FCM 服务未初始化');
        return false;
      }

      await _firebaseMessaging.unsubscribeFromTopic(topic);
      debugPrint('成功取消订阅主题: $topic');
      return true;
    } catch (e) {
      debugPrint('取消订阅主题失败: $e');
      return false;
    }
  }

  // 获取当前 token
  String? get currentToken => _fcmToken;

  // 监听 token 刷新
  void listenToTokenRefresh() {
    _firebaseMessaging.onTokenRefresh.listen((newToken) {
      _fcmToken = newToken;
      debugPrint('FCM Token 已刷新: $newToken');
    });
  }

  // 初始化 FCM
  Future<bool> initialize() async {
    try {
      debugPrint('开始初始化 FCM...');

      // 监听 token 刷新
      listenToTokenRefresh();

      // 处理前台消息
      FirebaseMessaging.onMessage.listen((RemoteMessage message) {
        debugPrint('收到前台消息: ${message.notification?.title}');
        // 这里可以添加本地通知显示逻辑
      });

      // 处理后台消息点击
      FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
        debugPrint('用户点击了后台消息: ${message.notification?.title}');
      });

      // 处理应用启动时的消息
      RemoteMessage? initialMessage = await _firebaseMessaging
          .getInitialMessage();
      if (initialMessage != null) {
        debugPrint('应用启动时的消息: ${initialMessage.notification?.title}');
      }

      _isInitialized = true;
      debugPrint('FCM 初始化成功');
      return true;
    } catch (e) {
      debugPrint('初始化 FCM 失败: $e');
      return false;
    }
  }

  // 检查是否已初始化
  bool get isInitialized => _isInitialized;
}
